import React, {useState, useEffect, useRef, forwardRef, useImperativeHandle} from 'react';
import {
    Image,
    Platform, ScrollView,
    StyleSheet, Text,
    TouchableOpacity, View
} from 'react-native';

import Modal from "react-native-modal";
import {windowHeight, windowWidth} from "../../utils/config";
import {useStatisticsEvents} from "../../hooks/useStatisticsEvents";
import * as S from "../Header/styles";
import {showToast} from "../../utils/toast";

const icon_uncheck = require('../../assets/images/icon_uncheck.png');
const icon_checked = require('../../assets/images/icon_checked.png');
const icon_clear = require('../../assets/images/clear.png');

const EventsModal = forwardRef((props, ref) => {

    const [ showModal, setShowModal ] = useState(false);
    const { loadEventList,eventObj,setEventObjData } = useStatisticsEvents();
    const [eventList, setEventList] = useState([]);

    useEffect(()=>{
        loadEventList().then(function (response) {
            // console.log('-EventsModal--loadEventList--response-',response)
            if (response?.code === 0) {
                setEventList(response?.data || []);
            }
        });
    },[])

    useImperativeHandle(ref,()=>({
        showModal: () => {
            openModal();
        },
        hideModal: () => {
            closeModal();
        },
    }))

    const openModal = () => {
        setShowModal(true);
    }

    const closeModal = () => {
        setShowModal(false);
    }

    const clickConfirm = () => {
        closeModal();
        if (Object.keys(eventObj).length === 0) {
            showToast("error", "出错了", '请选择事件');
            return;
        }
        let events = [];
        Object.keys(eventObj).map((key)=>{
            events.push({
                id: key,
                level: eventObj[key].level
            })
        })
        props.callback&&props.callback(events);
    }

    const clickItem = (item,level) => {
        let newEventObj = eventObj;
        if (newEventObj.hasOwnProperty(item.id)) {
            delete newEventObj[item.id];
        } else {
            newEventObj[item.id] = {
                id: item.id,
                level: level
            };
        }
        setEventObjData(JSON.parse(JSON.stringify(newEventObj)));
    }

    let duration = 100;
    let outduration = 500;

    // console.log('---EventsModal-state-',eventList)
    return (
        <View>
            <Modal
                backdropOpacity={0.5}
                animationInTiming={duration}
                animationOutTiming={outduration}
                backdropTransitionInTiming={duration}
                backdropTransitionOutTiming={outduration}
                coverScreen={true}
                statusBarTranslucent
                style={styles.modalView}
                isVisible={showModal}
                deviceWidth={windowWidth}
                onBackdropPress={closeModal}
            >
                <View style={styles.modalContent}>
                    <View style={styles.topModalView}>
                        <Text style={styles.topModalText}>选择事件</Text>
                        <TouchableOpacity onPress={()=>{
                            closeModal();
                        }} activeOpacity={0.8}>
                            <Image style={styles.clearIcon} source={icon_clear}/>
                        </TouchableOpacity>
                    </View>
                    <View style={styles.midModalContentView}>
                        <ScrollView>
                        {
                            eventList.map((item,index)=>{
                                return (
                                    <View style={styles.midModalItemView} key={'item_'+index}>
                                        <TouchableOpacity style={styles.midModalItemTitleView} onPress={()=>clickItem(item,1)}>
                                            <Image style={styles.checkIcon} source={eventObj.hasOwnProperty(item?.id) ? icon_checked : icon_uncheck}/>
                                            <Text style={styles.midModalItemText}>{item.name}</Text>
                                        </TouchableOpacity>
                                        {
                                            item.children&&item.children.map((seg,segIndex)=>{
                                                return (
                                                    <View key={'segIndex_'+segIndex}>
                                                        <TouchableOpacity style={styles.midModalItemChildrenView} onPress={()=>clickItem(seg,2)}>
                                                            <Image style={styles.checkIcon} source={eventObj.hasOwnProperty(seg?.id) ? icon_checked : icon_uncheck}/>
                                                            <Text style={styles.midModalItemText}>{seg.name}</Text>
                                                        </TouchableOpacity>
                                                        {
                                                            seg.children&&seg.children.map((s,sIndex)=>{
                                                                return (
                                                                    <TouchableOpacity style={styles.midModalItemSubChildrenView} key={'s_'+sIndex} onPress={()=>clickItem(s,3)}>
                                                                        <Image style={styles.checkIcon} source={eventObj.hasOwnProperty(s?.id) ? icon_checked : icon_uncheck}/>
                                                                        <Text style={styles.midModalItemText}>{s?.name}</Text>
                                                                    </TouchableOpacity>
                                                                )
                                                            })
                                                        }
                                                    </View>
                                                )
                                            })
                                        }
                                    </View>
                                )
                            })
                        }
                        </ScrollView>
                    </View>
                    <View style={styles.bottomButtonItem}>
                        <TouchableOpacity
                            style={styles.bottomButton}
                            onPress={clickConfirm}
                            activeOpacity={1}>
                            <Text style={styles.bottomButtonText}>
                                确认选择
                            </Text>
                        </TouchableOpacity>
                    </View>
                </View>

            </Modal>
        </View>
    );
});

export default EventsModal;

const styles = StyleSheet.create({
    modalView: {
        flex: 1,
        margin: 0,
        justifyContent: 'flex-end',
    },
    modalContent: {
        width: '100%',
        backgroundColor: '#fff',
        paddingHorizontal: 16,
        justifyContent: 'flex-end',
        height: parseInt(String(windowHeight * 0.67)),
        borderTopRightRadius: 20,
        borderTopLeftRadius: 20,
    },
    topModalView: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        height: 72,
    },
    topModalText: {
        color: 'rgba(44, 44, 46, 1)',
        fontSize: 18,
        fontWeight: 'bold',
    },
    midModalContentView: {
        backgroundColor: '#fff',
        maxHeight: parseInt(String(windowHeight * 0.67 - 72 - 50 - 30)),
    },
    bottomButtonItem: {
        width: '100%',
        alignItems: 'center',
        marginBottom: 30,
    },
    bottomButton: {
        backgroundColor: 'rgba(198, 224, 247, 1)',
        width: '100%',
        height: 50,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 16,
    },
    bottomButtonText: {
        color: 'rgba(65, 79, 102, 1)',
        fontSize: 14,
    },
    midModalItemView: {
    },
    midModalItemTitleView: {
        paddingLeft: 16,
        backgroundColor: 'rgba(250, 250, 250, 1)',
        paddingVertical: 10,
        marginBottom: 5,
        flexDirection: 'row',
        alignItems: 'center',
    },
    midModalItemChildrenView: {
        backgroundColor: 'rgba(250, 250, 250, 1)',
        paddingVertical: 10,
        marginBottom: 5,
        paddingLeft: 32,
        flexDirection: 'row',
        alignItems: 'center',
    },
    midModalItemSubChildrenView: {
        backgroundColor: 'rgba(250, 250, 250, 1)',
        paddingVertical: 10,
        marginBottom: 5,
        paddingLeft: 48,
        flexDirection: 'row',
        alignItems: 'center',
    },
    midModalItemText: {
        marginLeft: 5,
        color: 'rgba(44, 44, 46, 1)',
    },
    checkIcon: {
        width: 16,
        height: 16,
    },
    clearIcon: {
        width: 40,
        height: 40,
    }
});
